/*
 * author      : dormi330 
 * date        : 2018/7/19
 * description : 事件分发
 */

package com.deep.trade.application;

import com.deep.trade.adaptor.required.mq.MsgReceiver;
import com.deep.trade.adaptor.required.mq.MsgSender;
import com.deep.trade.adaptor.required.mq.UniqueMessageHandler;
import com.deep.trade.common.BaseEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class EventHub {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private MsgSender msgSender;

    @Autowired
    private MsgReceiver msgReceiver;

    public void publishEvent(BaseEvent event) {
        logger.info("publishEvent = {}}", event.uglyString());
        try {
            // event to message
            msgSender.sendMsg(event.getType(), event.toMessage());
        } catch (IOException e) {
            logger.error("publish event fail");
            e.printStackTrace();
        }
    }

    public void registerEvent(String type, UniqueMessageHandler handler) {
        logger.info("registerEvent");
        try {
            msgReceiver.register(type, handler);
        } catch (IOException e) {
            logger.error("registerEvent fail");
            e.printStackTrace();
        }

    }
}
